<template>
  <!-- 内容 -->
  <div class="main">
    <div class="container">
      <h6><b class="square"></b> 相关帖子</h6>
      <!-- 帖子列表 -->
      <ul class="list-unstyled mt-4">
        <li class="media pb-3 pt-3 mb-3 border-bottom" v-for="record in records" :key="record.post.id">
          <router-link :to="'/profile/' + record.user.id">
            <img :src="record.user.headerUrl" class="mr-4 rounded-circle" alt="用户头像" />
          </router-link>
          <div class="media-body">
            <h6 class="mt-0 mb-3">
              <router-link :to="'/discuss/detail/' + record.post.id" v-html="record.post.title" />
            </h6>
            <div class="mb-3" v-html="record.post.content" />
            <div class="text-muted font-size-12">
              <u class="mr-3">{{ record.user.username }}</u> 发布于 <b>{{ record.post.createTime }}</b>
              <ul class="d-inline float-right">
                <li class="d-inline ml-2">赞 {{ record.likeCount }}</li>
                <li class="d-inline ml-2">|</li>
                <li class="d-inline ml-2">回复 {{ record.post.commentCount }}</li>
              </ul>
            </div>
          </div>
        </li>
      </ul>
      <!-- 分页 -->
      <div class="mt-5" v-if="total > 0">
        <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="pageSizes"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import Search from '@/api/search'
import { useSearchStore } from '@/store/modules/search'

const route = useRoute()

const searchStore = useSearchStore()

const records = ref([])

const small = ref(false)
const background = ref(false)
const disabled = ref(false)

const total = ref(0)
const pageSizes = ref([5, 10, 20, 25])
const currentPage = ref(1)
const pageSize = ref(5)

onMounted(async () => {
  searchStore.keyword = route.query.q
  search()
})

// 当参数更改时重新搜索
watch(
  () => route.query.q,
  async newSearch => {
    searchStore.keyword = route.query.q
    await search()
  }
)

const search = async () => {
  Search.search(route.query.q, currentPage.value, pageSize.value).then(async res => {
    total.value = res.total
    records.value = res.records
    currentPage.value = res.current
    pageSize.value = res.size
  })
}

const handleSizeChange = async () => {
  search()
}

const handleCurrentChange = async () => {
  search()
}
</script>
